package com.linkwechat.wecom.factory.impl.kf;

import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.wecom.client.WeKfClient;
import com.linkwechat.wecom.domain.dto.kf.*;
import com.linkwechat.wecom.domain.vo.WxCpXmlMessageVO;
import com.linkwechat.wecom.factory.WeEventStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2022-1-15.
 */
@Slf4j
@Component("kf_msg_or_event")
public class WeCallbackSyncMsgImpl extends WeEventStrategy {
    @Autowired
    WeKfClient weKfClient;

    @Autowired
    private RedisCache cursorCache;

    @Override
    public void eventHandle(WxCpXmlMessageVO message) {
        SyncMsgDto syncMsgDto = new SyncMsgDto();
        syncMsgDto.setToken(message.getToken());
        syncMsgDto.setLimit(10);
        SyncMsgResDto syncMsgResDto;

        int hasMore=1;
        //while(hasMore==1) {
            if(cursorCache.getCacheObject("wwb72c0d797054d1d9_kf")!=null){
                syncMsgDto.setCursor(cursorCache.getCacheObject("wwb72c0d797054d1d9_kf"));
            }
            syncMsgResDto = weKfClient.syncMsg(syncMsgDto);

            List<WekfSyncMsgModel> msgList = syncMsgResDto.getMsgList();
            for(WekfSyncMsgModel m: msgList){
                if(m.getMsgtype().equals("event")){
                    WeKfSyncMsgEnterSession weKfSyncMsgEnterSession = (WeKfSyncMsgEnterSession) m.getEvent();
                    ServiceStateTransDto serviceStateTransDto = new ServiceStateTransDto();
                    serviceStateTransDto.setOpen_kfid(weKfSyncMsgEnterSession.getOpenKfid());
                    serviceStateTransDto.setService_state(3);
                    serviceStateTransDto.setExternal_userid(weKfSyncMsgEnterSession.getExternalUserid());
                    serviceStateTransDto.setServicer_userid(weKfSyncMsgEnterSession.getSceneParam());
                    try {
                        ServiceStateTransResDto res = weKfClient.transServiceState(serviceStateTransDto);
                    } catch (ForestRuntimeException e) {
                        continue;
                    }

                }
            }

            cursorCache.setCacheObject("wwb72c0d797054d1d9_kf", syncMsgResDto.getNextCursor());
            hasMore = syncMsgResDto.getHasMore();

        //}




    }
}
